package com.school.demo.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.school.demo.model.auto.*;
import com.school.demo.model.auto.Account;
import com.school.demo.service.*;
import com.school.demo.util.UserUitl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: demo
 * @description: 实现自定义Realm
 * @author: Charlotte
 * @create: 2021-03-02 10:06
 **/
public class MyRealm extends AuthorizingRealm {

    @Autowired
    IUserService userService;
    @Autowired
    IAccountService accountService;
    @Autowired
    IUserRoleService userRoleService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IRolePermissionService rolePermissionService;
    @Autowired
    IPermissionService permissionService;


    //提供权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //记录用户的所有角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//权限信息

        //获取当前登录对象
        Subject subject = SecurityUtils.getSubject();
        //拿到userId
        Integer id = (Integer) subject.getPrincipal();

        //查询权限信息
        List<Permission> permissions = new ArrayList<>();
        List<UserRole> userRoles = new ArrayList<>();
        List<String> permissionList = new ArrayList<>();


        //查询user_role表，获取所有角色
        QueryWrapper<UserRole> urq = new QueryWrapper<>();
        urq.lambda().eq(UserRole::getUserId,id).eq(UserRole::getDeleted,0);
        userRoles = userRoleService.list(urq);

        //查询role_permission表，获取所有权限
        List<Long> roleList = new ArrayList<>();
        List<RolePermission> rolePermissions= new ArrayList<>();
        for (UserRole ur : userRoles) {
            roleList.add(ur.getRoleId());
        }
        QueryWrapper<RolePermission> rpq = new QueryWrapper<>();
        rpq.lambda().in(RolePermission::getRoleId,roleList);
        rolePermissions = rolePermissionService.list(rpq);

        //查询所有权限
        List<Long> permissionIDList = new ArrayList<>();
        for (RolePermission rp : rolePermissions) {
            permissionIDList.add(rp.getPermissionId());
        }
        QueryWrapper<Permission> pq = new QueryWrapper();
        pq.lambda().in(Permission::getId,permissionIDList).eq(Permission::getDeleted,0);
        permissions = permissionService.list(pq);
        for (Permission p: permissions) {
            permissionList.add(p.getCode());
        }

        //添加权限
        info.addStringPermissions(permissionList);

        return info;
    }

    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        //获取用户名密码
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;

        //验证用户名是否合法
        if (UserUitl.isPhone(token.getUsername()) || UserUitl.isEmail(token.getUsername())){
            String log = "用户"+token.getUsername()+"匹配成功，正在登录...";
            System.out.println(log);
        }else{
            String log = "用户"+token.getUsername()+"匹配失败！";
            System.out.println(log);
            return null;
        }

        //验证用户是否存在
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Account::getOpenCode,token.getUsername());
        Account account=accountService.getOne(queryWrapper);

        if (account == null){
            return null;
        }

        User user = userService.getById(account.getUserId());

        return new SimpleAuthenticationInfo(user.getId()/*登录用户的资源可以在授权中拿到*/,user.getPassword(),"");
    }
}
